package com.sdx.console.crm.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ibeetl.admin.core.service.RedisService;
import com.sdx.console.common.wx.WxApi;
import com.sdx.console.crm.entity.CrmMessage;
import com.sdx.console.crm.entity.CrmSession;
import com.sdx.console.customer.entity.CustomerInfo;
import com.sdx.console.wx.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 */
@Service
public class CrmChatService {

    //客户消息队列:n
    private static final String MESSAGE_QUEUE = "crm_message_customer";

    @Autowired
    private SQLManager sqlManager;

    private static final String SQL = "crm.chat";

    @Autowired
    private CrmSessionService  crmSessionService;

    @Autowired
    private CrmMessageService crmMessageService;

    @Autowired
    private RedisService redisService;


    /**
     * 给客服发送消息数据
     * @param crmMessage
     * @return
     */
    public String sendParam( CrmMessage crmMessage){
        Map<String, Object> map = new HashMap<>();
        String customerId = crmMessage.getCustomerId();
        String openid = crmMessage.getOpenid();
        Integer sessionId = crmMessage.getSessionId();
        map.put("customerId", customerId);
        map.put("openid", openid);
        CustomerInfo customerInfo =  new CustomerInfo();
        try {
            customerInfo = sqlManager.selectSingle(SQL + ".findCustomerInfo", map, CustomerInfo.class);
        } catch (Exception e) {

        }
        JSONObject jsonObjec = new JSONObject();
        jsonObjec.put("id",sessionId);
        String avatar = "https://static.51sdx.com/p/html/kefu/yonghu.png";
        String name = "客户"+sessionId;
        if(customerInfo!=null){
            if(StringUtils.isNotBlank(customerInfo.getPhone())){
                name = customerInfo.getPhone();
            }
            if(StringUtils.isNotBlank(customerInfo.getWxPicurl())){
                avatar = customerInfo.getWxPicurl();
            }
        }
        jsonObjec.put("avatar",avatar);
        jsonObjec.put("name",name);
        jsonObjec.put("content",crmMessage.getSafeContent());
        jsonObjec.put("time",crmMessage.getCreateTime());
        return jsonObjec.toJSONString();
    }

    /**
     * 给客户发送消息数据
     * @param json
     */
    public void sendMessage(JSONObject json){
        try {

            String msg = json.getString("msg");
            int toUser = json.getIntValue("toUser");
            int userId = json.getIntValue("userId");

            //修改会话最后操作时间 类型
            crmSessionService.sendUpdate(toUser,2);

            //修改坐席操作时间
            updateCrmRepresentive(userId,"1");

            //得到会话数据
            CrmSession crmSession = crmSessionService.getCrmSessionById(toUser);
            //插入消息
            crmMessageService.insert(crmSession,msg);
            //获取accessToken

            //如果是微信或小程序消息直接发送   H5消息存入消息队列
            if(crmSession.getSourceType() == 1||crmSession.getSourceType() == 3){
                //(String accessToken,String openId,String txt)
//                String openId = "oG6LYsrt5Ig-HRHbLqbElNIyZy0A";
                String wxTokenURL = sqlManager.selectSingle(SQL + ".selectWxTokenURL", null,String.class);
                String accessToken = null;
                try {
                    accessToken = HttpUtils.httpGet(wxTokenURL+crmSession.getAppId());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(accessToken!=null){
                    WxApi.sendTextMessage(accessToken,crmSession.getOpenId(),msg);
                }
            }else{
                CrmMessage crmMessage = new CrmMessage();
                crmMessage.setCreateTime(new Date());
                crmMessage.setCustomerId(crmSession.getCustomerId());
                crmMessage.setSessionId(crmSession.getSessionId());
                crmMessage.setSafeContent(msg);
                crmMessage.setUserId(userId);
                redisService.firstIn(MESSAGE_QUEUE, JSON.toJSONString(crmMessage));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭会话
     * @param userId
     */
    public void closeSession(String userId){
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        sqlManager.update(SQL + ".closeCrmSession",map);
    }

    /**
     * 修改坐席操作时间
     * @param userId
     * @param serviceStatus
     */
    public void updateCrmRepresentive(Integer userId,String serviceStatus){
        //修改坐席操作时间 和状态
        Map<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("serviceStatus",serviceStatus);
        sqlManager.update(SQL+".updateCrmRepresentive",map);
    }

}
